// 大数据作业第二题
// author ：lbc 
package homework1;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

public class CopyToLocalFile {
    public static void main(String[] args) throws IOException, URISyntaxException {
        Configuration conf = new Configuration();
        String hdfsPath = "hdfs://localhost:9000";
        FileSystem hdfs = FileSystem.get(new URI(hdfsPath), conf);

        String from_HDFS = "hdfstest/touchfile.txt";
        String to_Linux = "/root/trash/touchfile.txt";
        if (!FileExist(to_Linux)) {
            hdfs.copyToLocalFile(false, new Path(from_HDFS), new Path(to_Linux));
        } else {
            String newPath = FindFileName(to_Linux);
            hdfs.copyToLocalFile(false, new Path(from_HDFS), new Path(newPath));
            System.out.println("File already exist, rename as:" + newPath);
        }
        System.out.println("Finish!");

    }

    public static boolean FileExist(String File_path) {
        File file = new File(File_path);
        if (file.exists()) {
            return true;
        }
        return false;
    }

    public static String FindFileName(String FilePath) {
        int num = 1;
        while (true) {
            File fp = new File(FilePath + String.valueOf(num));
            if (!fp.exists())
                break;
            num++;
        }
        return FilePath + String.valueOf(num);
    }

}
